﻿using System;
using System.ComponentModel.DataAnnotations;

namespace VisionCloud.Domain.ModelAttribute
{
    /// <summary>
    /// 数据库排序order by特性
    /// </summary>
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter,
        AllowMultiple = false)]
    public class OrderByFieldAttribute : ValidationAttribute
    {
        /// <summary>
        /// 自定义错误信息
        /// </summary>
        internal static string errorMessageString = "Sorting of this field {0} is not supported";

        /// <summary>
        /// 支持的排序字段的type
        /// </summary>
        private readonly Type soureceType;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="soureceType">支持的排序字段的type：typeof(T)</param>
        public OrderByFieldAttribute(Type soureceType) : base(() => errorMessageString)
        {
            this.soureceType = soureceType;
            this.ErrorMessageResourceType = soureceType;
        }

        /// <summary>
        /// 错误信息
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public override string FormatErrorMessage(string name)
        {
            this.ErrorMessage = errorMessageString;
            return string.Format(errorMessageString, name);
        }

        /// <summary>
        /// 检验
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public override bool IsValid(object value)
        {
            var str = value?.ToString();

            if (string.IsNullOrEmpty(str))
                return true;

            var arr = str.Split(",");
            foreach (var item in arr)
            {
                var info = this.soureceType.GetProperty(item);
                if (info == null)
                {
                    return false;
                }
            }
            

            return true;
        }
    }
}
